package com.example.stompdemo.test;

import org.springframework.web.socket.WebSocketSession;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * socket管理器  如果只用广播 可以不使用
 */
public class SocketManager {
    private static ConcurrentHashMap<String, WebSocketSession> manager = new ConcurrentHashMap<String, WebSocketSession>();

    public static void add(String key, WebSocketSession webSocketSession) {
        System.out.println("新添加webSocket连接  " + key);
        manager.put(key, webSocketSession);
    }

    public static void remove(String key) {
        System.out.println("移除webSocket连接  " + key);
        manager.remove(key);
    }

    public static WebSocketSession get(String key) {
        System.out.println("获取webSocket连接  " + key);
        return manager.get(key);
    }

    public static List<String> getList() {

        List<String> list = new ArrayList<>();

        Enumeration<String> keys = manager.keys();
        if(keys !=null && keys.hasMoreElements()){
            String element = keys.nextElement();
            while (keys.hasMoreElements()){
                list.add(element);
                element = keys.nextElement();
            }
        }
        return list;
    }

    public static List<Map<String,String>> getArrayList() {

        List<Map<String,String>> list = new ArrayList<>();

        manager.forEach((key,value)->{
            Map<String,String> map = new HashMap<>();
            map.put("token", key);
            map.put("sessionId", value.getId());
            list.add(map);
        });
        return list;
    }
}
